package com.yksj.healthtalk.ui.doctor;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshScrollView;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.TickMesg;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.views.ServiceTypeView;
import com.yksj.healthtalk.ui.views.ServiceTypeView.ServiceTypeSubContentListener;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * VIP服务
 * @author Administrator
 * 
 */
public class DoctorCommonServiceActivity extends BaseFragmentActivity implements
		OnClickListener, OnDilaogClickListener ,ServiceTypeSubContentListener{
	public static final int REQUESTCODE = 1;
	private EditText mDescribeEt;// 医生说明
	private ServiceTypeView mServiceTypeView;
	private LinearLayout buttons;// 下面的按钮
	private String doctorId; 
	private CustomerInfoEntity mCustomerInfoEntity;
	private TextView mTime;// 购买时间
	private TextView mServiceMoney;// 金额
	private TextView mServiceName;// 服务名称
	private String response;
	private PullToRefreshScrollView scrollView;
	private ArrayList<TickMesg> mesgs;
	private TextView mServiceStart;
	private TextView mServiceEnd;
	private JSONObject totalObject;
	private TickMesg mesg;
	private TextView mServiceContent1;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_common_service);
		initWidget();
		initData();
	}

	// 初始化控件
	private void initWidget() {
		initTitle();
		scrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
		scrollView.setLayoutInvisible(); 
		mDescribeEt = (EditText) findViewById(R.id.describe);
		mTime = (TextView) findViewById(R.id.time);
		mServiceStart = (TextView)findViewById(R.id.service_start);
		mServiceEnd= (TextView)findViewById(R.id.service_end);
		mServiceMoney = (TextView) findViewById(R.id.service_money);
		mServiceName = (TextView) findViewById(R.id.service_name);
		mServiceTypeView = (ServiceTypeView) findViewById(R.id.service_type_view);
		buttons = (LinearLayout) findViewById(R.id.buttons_lin);
		mServiceContent1=(TextView)findViewById(R.id.service_content1);

		titleTextV.setText("VIP服务");

		titleLeftBtn.setOnClickListener(this);

	}
	
	// 服务内容
		public void onClickServcieContent(View v) {
			Intent intent = new Intent(getApplicationContext(),DoctorServiceActivity.class);
			if (mesgs != null && mesgs.size() != 0) {
				intent.putExtra("ORIDERID",mesgs.get(0).getORDER_ID());
			}else {
				return;
			}
			intent.putExtra("isbuy", true);
			startActivity(intent);
		}
//		@Override
//		protected void onStart() {
//			super.onStart();
//			Intent intent =new Intent(this,CoreService.class);
//			intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
//			intent.putExtra("className",this.getClass().getName());
//			startService(intent);
//		}
	private void initData() {
		if (response == null) {
			Intent intent = getIntent();
			mCustomerInfoEntity = (CustomerInfoEntity) intent.getExtras().get("mCustomerInfoEntity");
			response = intent.getExtras().getString("response");
			doctorId = mCustomerInfoEntity.getId();
		}
		try {
			totalObject = JSON.parseObject(response);
			
			//医生说明
			if(TextUtils.isEmpty(totalObject.getString("SERVICE_ITEM_DESC"))){
				mDescribeEt.setText("欢迎您的光临，很高兴为您服务");
			}else{
				mDescribeEt.setText(totalObject.getString("SERVICE_ITEM_DESC"));
			}
			JSONArray json=(JSONArray) totalObject.get("TickMesg");
			JSONObject json2= (JSONObject) json.get(0);
//			json=(JSONObject) totalObject.get("TickMesg");
			//所享受服务
			mServiceContent1.setText(json2.getString("SERVICE_CONTENT"));

			
//			HttpRestClient.doHttpMyDoctorOrderDetail(SmartFoxClient.getLoginUserId(),totalObject.getString("ORDER_ID"),totalObject.getString("PAY_ID"), new JsonHttpResponseHandler(){
//      @Override
//    public void onSuccess(int statusCode,
//    		org.json.JSONObject response) {
//    	super.onSuccess(statusCode, response);
//		
//    	mServiceContent1.setText(response.optString("SERVICE_CONTENT"));
//      }});
			int witchPage = totalObject.getIntValue("witchPage");
			if (SmartFoxClient.getLoginUserInfo().isDoctor()) {
				witchPage = 1;
			}
			switch (witchPage) {
			// 未购买
			case 1:
				initBottomButton(1);
				findViewById(R.id.start_end_time).setVisibility(View.GONE);//服务购买时间和截止时间
				mServiceTypeView.setVisibility(View.VISIBLE);//服务选择按钮
				findViewById(R.id.service_content).setVisibility(View.GONE);//所享受的服务内容
				findViewById(R.id.pay_time).setVisibility(View.GONE);//购买时间
				mServiceTypeView.addData(this, totalObject.getJSONArray("TickMesg"));
				break;
			case 2://已经购买
				mesgs = (ArrayList<TickMesg>) JSON.parseArray(totalObject.getJSONArray("TickMesg").toString(),TickMesg.class);
				initBottomButton(1);
				//已经购买不显示温馨提示
				findViewById(R.id.message).setVisibility(View.GONE);
				findViewById(R.id.message_content).setVisibility(View.GONE);
				Button button = (Button) findViewById(BUTTON.pay.getId());
				button.setText("看医生");
				button.setBackgroundResource(R.drawable.green_button_selector);
				button.setTextColor(getResources().getColor(R.color.text_green));
				mServiceTypeView.setVisibility(View.GONE);
				findViewById(R.id.start_end_time).setVisibility(View.VISIBLE);
				findViewById(R.id.service_content).setVisibility(View.VISIBLE);//所享受服务
				findViewById(R.id.pay_time).setVisibility(View.GONE);
				if (mesgs != null && mesgs.size()!=0) {
//					String time = mesgs.get(0).getORDER_CREATE_TIME();
//					mTime.setText(time);
					TickMesg tickMesg = mesgs.get(0);
					if (!TextUtils.isEmpty(tickMesg.getSERVICE_GOLD())) {
						mServiceMoney.setText(tickMesg.getSERVICE_GOLD() + "元");
					}else {
						mServiceMoney.setText("");
					}
					mServiceName.setText(tickMesg.getSERVICE_TYPE_SUB());
					if (!TextUtils.isEmpty(tickMesg.getORDER_CREATE_TIME())) {
						mServiceStart.setText(TimeUtil.getFormatTime(tickMesg.getORDER_CREATE_TIME()));
					}else {
						mServiceStart.setText("");
					}
					if (!TextUtils.isEmpty(tickMesg.getSERVICE_END())) {
						mServiceEnd.setText(TimeUtil.getFormatTime(tickMesg.getSERVICE_END()));
					}else {
						mServiceEnd.setText("");
					}
				}
				break;
			// 未支付
			case 3:
				initBottomButton(2);
				findViewById(R.id.start_end_time).setVisibility(View.GONE);
				mServiceTypeView.setVisibility(View.GONE);
				findViewById(R.id.service_content).setVisibility(View.VISIBLE);//所享受服务
				findViewById(R.id.pay_time).setVisibility(View.VISIBLE);
				mesgs = (ArrayList<TickMesg>) JSON.parseArray(totalObject.getJSONArray("TickMesg").toString(),TickMesg.class);
				if (mesgs != null && mesgs.size() == 1) {
					String time = mesgs.get(0).getORDER_CREATE_TIME();
					if (!TextUtils.isEmpty(time)) {
						time = TimeUtil.getFormatTime(time);
					}else {
						time = "";
					}
					mTime.setText(time);
					mServiceMoney.setText(mesgs.get(0).getSERVICE_GOLD() + "元");
					mServiceName.setText(mesgs.get(0).getSERVICE_TYPE_SUB());
				}
				break;
			}
		} catch (Exception e) {
		}
	}

	// 初始化按钮
	private void initBottomButton(int j) {
		Button button;
		for (int k = 0; k < buttons.getChildCount(); k++) {
			buttons.getChildAt(k).setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < buttons.getChildCount(); i++) {
			if (i == buttons.getChildCount() - 1 && j == 1) {
				button = (Button) buttons.getChildAt(i);
				button.setText("购买");
				button.setTextColor(getResources().getColor(R.color.text_orange));
				button.setBackgroundResource(R.drawable.orange_button_selector);
				button.setId(BUTTON.pay.getId());
				button.setOnClickListener(this);
			} else if (j == 2) {
				if (i == buttons.getChildCount() - 2 || i == buttons.getChildCount() - 1) {
					button = (Button) buttons.getChildAt(buttons.getChildCount() - 2);
					button.setText("支付");
					button.setTextColor(getResources().getColor(R.color.text_green));
					button.setBackgroundResource(R.drawable.login_button);
					button.setId(BUTTON.pay.getId());
					button.setOnClickListener(this);
					button = (Button) buttons.getChildAt(buttons.getChildCount() - 1);
					button.setText("删除");
					button.setTextColor(getResources().getColor(R.color.tab_txt_orange));
					button.setBackgroundResource(R.drawable.orange_button_selector);
					button.setId(BUTTON.delete.getId());
					button.setOnClickListener(this);
				} else {
					buttons.getChildAt(i).setVisibility(View.GONE);
				}
			} else {
				buttons.getChildAt(i).setVisibility(View.GONE);
			}
		}
	}

	@Override
	public void onClick(View v) {
		//普通咨询未付费点击服务的类型 价格为0 的按钮变化 
		if (v.getTag() != null && v.getTag() instanceof TickMesg) {
			TickMesg mesg  = 	(TickMesg)v.getTag(); 
				Button	button = (Button) findViewById(BUTTON.pay.getId());
				 if (mesg.getSERVICE_PRICE().equals("0") || SmartFoxClient.getLoginUserInfo().isDoctor() ) {
					button.setText("看医生");
					button.setBackgroundResource(R.drawable.login_button);
					button.setTextColor(getResources().getColorStateList(R.color.text_green));
				}else {
					button.setText("购买");
					button.setBackgroundResource(R.drawable.orange_button_selector);
					button.setTextColor(getResources().getColorStateList(R.color.text_orange));
				}
		}else {
			switch (v.getId()) {
			case R.id.title_back:
				onBackPressed();
				break;
			default:
				if (v.getId() == BUTTON.pay.getId()) { 
					 if (mServiceTypeView.getVisibility() == View.VISIBLE) {// 未购买
						mesg = mServiceTypeView.getServiceTickMesg();
						if (SmartFoxClient.getLoginUserInfo().isDoctor()) {
							FriendHttpUtil.onItemClick(this, mCustomerInfoEntity);
						}else if (mesg != null) {
							HttpRestClient.doHttpWalletBalanceServlet(null,HttpRestClient.doHttpPayService(null,SmartFoxClient.getLoginUserId(), doctorId,"1", mesg.getSERVICE_ITEM_ID(),null,null,null,null,new AsyncHander(v.getId())), new AsyncHander(BUTTON.pay.getId()));
						}
					}else {//未支付和购买完成
						Button	button = (Button) findViewById(BUTTON.pay.getId());
						if (button.getText().toString().equals("看医生") || SmartFoxClient.getLoginUserInfo().isDoctor()) {//支付完成看医生直接调对话
							FriendHttpUtil.onItemClick(this, mCustomerInfoEntity);
						}else {
							HttpRestClient.doHttpWalletBalanceServlet(null,HttpRestClient.doHttpPayment(null,SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), mesgs.get(0).getSERVICE_TYPE_ID(), mesgs.get(0).getSERVICE_ITEM_ID(), mesgs.get(0).getSERVICE_TYPE_SUB_ID(),new AsyncHander(v.getId())), new AsyncHander(BUTTON.pay.getId()));
						}
					}
				} else if (v.getId() == BUTTON.delete.getId()) {
					if (mesgs != null && mesgs.size() == 1) {
						HttpRestClient.doHttpDeleteOrder(SmartFoxClient.getLoginUserId(), doctorId,mesgs.get(0).getORDER_ID(),new AsyncHander(v.getId()));
					}
				}
				break;
			}
		}
	}

	public enum BUTTON {
		pay(1), Time(2), alert(3), unsubscribe(4), delete(5),wallet(6);
		int id;

		BUTTON(int id) {
			this.id = id;
		}

		public int getId() {
			return id;
		}
	}

	class AsyncHander extends AsyncHttpResponseHandler {

		private int ButtonId;

		public AsyncHander(int id) {
			super(DoctorCommonServiceActivity.this);
			this.ButtonId = id;
		}

		@Override
		public void onSuccess(int statusCode, String content) {
			try {
				Object object = JSON.parse(content);
				if (object == null && ButtonId == BUTTON.delete.getId()) {//删除订单
					ToastUtil.showShort(getApplicationContext(), "删除订单成功");
					finish();
				}else if (object instanceof JSONObject) {
					JSONObject object2 = (JSONObject) object;
					if (object2.containsKey("error_message")) {
						SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), object2.getString("error_message"));
						return;
					}else if(object2.containsKey("LING") && ButtonId == BUTTON.pay.getId()){//价格为0 跳转到 聊天界面
						FriendHttpUtil.onItemClick(DoctorCommonServiceActivity.this, mCustomerInfoEntity);
					}else if (object2.containsKey("Balance")&& ButtonId == BUTTON.pay.getId()) {
						Intent intent = new Intent(getApplicationContext(),SelectPaymentOptionActivity.class);
						if(mesg != null){
							intent.putExtra("url", HttpRestClient.doHttpPayService(null,SmartFoxClient.getLoginUserId(), doctorId,"1", mesg.getSERVICE_ITEM_ID(),null,null,null,null,new AsyncHander(0)));
						}else{
							intent.putExtra("url", HttpRestClient.doHttpPayment(null,SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), mesgs.get(0).getSERVICE_TYPE_ID(), mesgs.get(0).getSERVICE_ITEM_ID(), mesgs.get(0).getSERVICE_TYPE_SUB_ID(),new AsyncHander(0)));
						}
						intent.putExtra("money",object2.getString("Balance"));
						intent.putExtra("BindPhone", object2.getString("BindPhone"));
						intent.putExtra("isSetPsw", object2.getString("isSetPsw"));
						intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
						startActivity(intent);
						finish();
					}
				}
			} catch (Exception e) {
			}
			super.onSuccess(statusCode, content);
		}

	}
	
	@Override
	public void onBackPressed() {
		if (getSupportFragmentManager().getBackStackEntryCount() >0) {
			getSupportFragmentManager().popBackStackImmediate();
		} else {
			finish();
		}
	}

//	@Override
//	public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
////		refresh();
//		scrollView.onRefreshComplete();
//	}

	/**
	 * 重新请求界面
	 */
	private void refresh() {
		HttpRestClient.doHttpEngageTheDialogue(SmartFoxClient.getLoginUserId(),
				doctorId, "1", new JsonsfHttpResponseHandler(this) {
					@Override
					public void onStart() {
						scrollView.setRefreshing();
						super.onStart();
					}

					@Override
					public void onSuccess(int statusCode, JSONArray response) {
						// TODO Auto-generated method stub
						super.onSuccess(statusCode, response);
					}

					@Override
					public void onSuccess(int statusCode,
							com.alibaba.fastjson.JSONObject response) {
						if (JsonParseUtils.filterErrorMessage(response) == null) {
							DoctorCommonServiceActivity.this.response = response.toString();
							initData();
						}
						super.onSuccess(statusCode, response);
					}

					@Override
					public void onFinish() {
						scrollView.onRefreshComplete();
						super.onFinish();
					}
				});
	}
	
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if (arg0 == REQUESTCODE && arg1== RESULT_OK) {
			refresh();  
		}
		super.onActivityResult(arg0, arg1, arg2);
	}

	@Override
	public void onDismiss(DialogFragment fragment) {
	}

	@Override
	public void onClick(DialogFragment fragment, View v) {//延时
		// TODO Auto-generated method stub
		HttpRestClient.doHttpDelayed(SmartFoxClient.getLoginUserId(), doctorId,mesgs.get(0).getORDER_ID(), new AsyncHander(BUTTON.Time.getId()));
	}

	//服务内容
	@Override
	public void onClickServiceTypeSubContent(int position) {
		if (mServiceTypeView != null && totalObject != null) {
			Intent intent = new Intent(getApplicationContext(),DoctorServiceActivity.class);
			intent.putExtra("userId", mCustomerInfoEntity.getId());
			intent.putExtra("service_type", "1");
			if (mServiceTypeView.getVisibility() == View.VISIBLE) {
				ArrayList<TickMesg> mesgs = (ArrayList<TickMesg>) JSON.parseArray(totalObject.getJSONArray("TickMesg").toString(),TickMesg.class);
				intent.putExtra("service_item_id", mesgs.get(position).getSERVICE_ITEM_ID());
			}else {
				return;
			}
			startActivity(intent);
		}
	}

}
